const isNeedToLogin = (callback) => {
	const token = uni.getStorageSync('token');
	if (token) {
		callback(true)
	} else {
		uni.showModal({
			title: '提示',
			content: '请先登录',
			success: (res) => {
				if (res.confirm) {
					gotoLogin()
				} else {
					callback(false)
				}
			}
		})
	}
}

const gotoLogin = () => {
	const currentPage = getCurrentPages()[getCurrentPages().length - 1]
	if (currentPage.route.includes('pages/login/index')) return
	const route = {
		options: currentPage.options,
		route: currentPage.route
	}
	uni.setStorageSync('route', JSON.stringify(route))

	uni.navigateTo({
		url: '/pages/login/index'
	});
}

const loginGoback = () => {
	const json = uni.getStorageSync('route')
	const route = JSON.parse(json);
	if (json && route.route) {
		let url = `/${route.route}`
		if (route.options) {
			url += `?${Object.keys(route.options).map(key => `${key}=${route.options[key]}`).join('&')}`
		}
		uni.reLaunch({
			url
		}); // 使用reLaunch方法跳转页面，避免返回时出现空白页面
		// uni.redirectTo({ url });
	} else {
		uni.switchTab({
			url: '/pages/tabbar/tab1/index'
		});
	}
	uni.setStorageSync('route', '');
}

export default {
	isNeedToLogin,
	gotoLogin,
	loginGoback
}